<route lang="json5" type="page">
{
  layout: 'default',
  needLogin: true,
  style: {
    navigationBarTitleText: '用电量统计详情',
    navigationBarBackgroundColor: '#4ECDC4',
    navigationBarTextStyle: 'white',
    backgroundColor: '#F5F7FA'
  },
}
</route>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'

// eslint-disable-next-line ts/no-require-imports
const echarts = require('../../../uni_modules/lime-echart/static/echarts.min.js')

// 图表组件引用
const pieChart = ref()
const barChart = ref()

// 当前用电量
const currentUsage = ref(710)

// 统计数据
const statisticsData = ref({
  totalAmount: 6508.5,
  reportDate: '2024年6月16日',
  meterNumber: '201105450485787',
  usage: 39800,
  lastReadDate: '2024.05.30',
  accountPeriod: '2024.06.16-至今',
})

// 报告周期选项
const periodOptions = ref(['周', '月', '年'])
const selectedPeriod = ref('月')

// 户号信息
const accountInfo = ref({
  accountNumber: '301-A',
})

// 日期选择器相关
const showDatePicker = ref(false)
const selectedDate = ref(new Date().getTime())

// 根据周期类型计算选择器类型
const pickerType = computed(() => {
  switch (selectedPeriod.value) {
    case '周':
      return 'date' // 选择具体日期，然后计算所在周
    case '月':
      return 'year-month' // 选择年月
    case '年':
      return 'year' // 选择年份
    default:
      return 'year-month'
  }
})

// 格式化显示的日期文本
const formattedDate = computed(() => {
  const date = new Date(selectedDate.value)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  switch (selectedPeriod.value) {
    case '周': {
      // 计算所在周
      const weekStart = new Date(date)
      const dayOfWeek = date.getDay()
      const diff = date.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1)
      weekStart.setDate(diff)
      const weekEnd = new Date(weekStart)
      weekEnd.setDate(weekStart.getDate() + 6)
      return `${year}年 (${formatShortDate(weekStart)}-${formatShortDate(weekEnd)})`
    }
    case '月':
      return `${year}年${month}月`
    case '年':
      return `${year}年`
    default:
      return `${year}年${month}月${day}日`
  }
})

// 获取周数
function getWeekNumber(date: Date): number {
  const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()))
  const dayNum = d.getUTCDay() || 7
  d.setUTCDate(d.getUTCDate() + 4 - dayNum)
  const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1))
  return Math.ceil((((d.getTime() - yearStart.getTime()) / 86400000) + 1) / 7)
}

// 格式化短日期
function formatShortDate(date: Date): string {
  const month = date.getMonth() + 1
  const day = date.getDate()
  return `${month}.${day}`
}

// 切换周期
function changePeriod(period: string) {
  selectedPeriod.value = period
  // 这里可以添加切换周期的逻辑
}

// 打开日期选择器
function openDatePicker() {
  showDatePicker.value = true
}

// 确认选择日期
function confirmDate(event: any) {
  selectedDate.value = new Date(event.value).getTime()
  showDatePicker.value = false
  // 这里可以添加日期变更后的数据更新逻辑
}

// 取消选择
function cancelDate() {
  showDatePicker.value = false
}

// 计算进度条宽度
const progressWidth = computed(() => {
  const usage = currentUsage.value
  const maxRange = 1000 // 设置最大范围
  const percentage = Math.min((usage / maxRange) * 100, 100)
  return `${percentage}%`
})

// 饼图数据
const pieOption = {
  tooltip: {
    trigger: 'item',
    formatter(params) {
      return `{title|${params.seriesName}}\n{name|${params.name}: }{value|${params.value}kw}\n{percent|占比: ${params.percent}%}`
    },
    backgroundColor: 'rgba(0,0,0,0.8)',
    textStyle: {
      color: '#fff',
      fontSize: 12,
      rich: {
        title: {
          color: '#fff',
          fontSize: 13,
          fontWeight: 'bold',
          lineHeight: 20,
        },
        name: {
          color: '#4ECDC4',
          fontSize: 12,
          lineHeight: 18,
        },
        value: {
          color: '#fff',
          fontSize: 12,
          fontWeight: 'bold',
          lineHeight: 18,
        },
        percent: {
          color: '#FFD93D',
          fontSize: 11,
          lineHeight: 18,
        },
      },
    },
    borderWidth: 0,
    padding: [8, 12],
  },
  legend: {
    bottom: '5%',
    left: 'center',
    itemWidth: 12,
    itemHeight: 12,
    itemGap: 25,
    textStyle: {
      fontSize: 14,
      color: '#333',
    },
    formatter(name) {
      const data = pieOption.series[0].data.find(item => item.name === name)
      return `${name}: ${data.value}kw`
    },
  },
  color: ['#4ECDC4', '#FFD93D', '#FF6B6B'],
  series: [
    {
      name: '用电分布',
      type: 'pie',
      radius: ['35%', '55%'],
      center: ['50%', '42%'],
      avoidLabelOverlap: true,
      itemStyle: {
        borderRadius: 3,
        borderColor: '#fff',
        borderWidth: 2,
      },
      label: {
        show: false,
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 12,
          fontWeight: 'bold',
        },
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)',
        },
      },
      labelLine: {
        show: true,
        length: 15,
        length2: 8,
        smooth: true,
      },
      data: [
        { value: 148, name: '谷' },
        { value: 250, name: '平' },
        { value: 108, name: '峰' },
      ],
    },
  ],
}

// 阶梯电量数据
const ladderData = ref([
  { type: '基础电费平', price: '0.6170', usage: '/', amount: 0 },
  { type: '基础电费谷', price: '0.3070', usage: '/', amount: 0 },
  { type: '基础电费峰', price: '0.7170', usage: '/', amount: 0 },
  { type: '二档增平', price: '0.7170', usage: '250', amount: 250 },
  { type: '二档增谷', price: '0.70', usage: '250', amount: 250 },
  { type: '二档增峰', price: '0.810', usage: '250', amount: 250 },
  { type: '三档增平', price: '0.710', usage: '250', amount: 250 },
  { type: '三档增谷', price: '0.70', usage: '/', amount: 0 },
  { type: '三档增峰', price: '1.50', usage: '/', amount: 0 },
])

// 柱状图数据
const barOption = {
  title: {
    text: '每日平用电量统计',
    left: 'center',
    textStyle: {
      fontSize: 14,
      fontWeight: 'normal',
      color: '#333',
    },
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
  },
  legend: {
    data: ['谷', '平', '峰'],
    bottom: '5%',
    itemWidth: 12,
    itemHeight: 12,
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '15%',
    containLabel: true,
  },
  xAxis: {
    type: 'category',
    data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    axisLabel: {
      color: '#666',
      fontSize: 10,
    },
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      color: '#666',
      fontSize: 10,
    },
    splitLine: {
      lineStyle: {
        color: '#E5E7EB',
        type: 'dashed',
      },
    },
  },
  color: ['#4ECDC4', '#FFD93D', '#FF6B6B'],
  series: [
    {
      name: '谷',
      type: 'bar',
      stack: 'total',
      data: [200, 180, 210, 220, 180, 250, 240],
    },
    {
      name: '平',
      type: 'bar',
      stack: 'total',
      data: [220, 200, 250, 300, 280, 320, 380],
    },
    {
      name: '峰',
      type: 'bar',
      stack: 'total',
      data: [150, 180, 200, 150, 200, 150, 200],
    },
  ],
}

// 初始化图表
onMounted(() => {
  setTimeout(async () => {
    // 初始化饼图
    if (pieChart.value) {
      const pieChartInstance = await pieChart.value.init(echarts)
      pieChartInstance.setOption(pieOption)
    }

    // 初始化柱状图
    if (barChart.value) {
      const barChartInstance = await barChart.value.init(echarts)
      barChartInstance.setOption(barOption)
    }
  }, 200)
})

// 格式化数字
function formatNumber(num: number): string {
  return num.toLocaleString()
}
</script>

<template>
  <view class="electricity-detail">
    <!-- 报告周期选择器 -->
    <view class="period-selector">
      <view class="account-info">
        <text class="account-label">
          户号:
        </text>
        <text class="account-number">
          {{ accountInfo.accountNumber }}
        </text>
      </view>
      <view class="period-tabs">
        <view
          v-for="period in periodOptions" :key="period" class="period-tab"
          :class="{ active: selectedPeriod === period }" @click="changePeriod(period)"
        >
          {{ period }}
        </view>
      </view>
    </view>

    <!-- 顶部统计卡片 -->
    <view class="top-card">
      <view class="card-header">
        <view class="meter-number">
          <text class="label">
            表号
          </text>
          <text class="number">
            {{ statisticsData.meterNumber }}
          </text>
        </view>
        <view class="date-info">
          <wd-datetime-picker
            v-model="selectedDate" :type="pickerType" :z-index="99999"
            @confirm="confirmDate" @cancel="cancelDate"
          >
            <template #default>
              <text class="report-time">
                报告时间：{{ formattedDate }}
              </text>
              <wd-icon name="arrow-down" size="24rpx" custom-class="ml-1" />
            </template>
          </wd-datetime-picker>
        </view>
      </view>

      <view class="amount-section">
        <text class="total-label">
          总计
        </text>
        <text class="total-amount">
          {{ formatNumber(statisticsData.totalAmount) }}元
        </text>
      </view>

      <view class="period-info">
        <text class="period-text">
          统计周期（{{ statisticsData.accountPeriod }}）
        </text>
      </view>
    </view>

    <!-- 用电量信息 -->
    <view class="usage-info">
      <view class="usage-item">
        <text class="usage-label">
          用电量
        </text>
        <text class="usage-value">
          {{ formatNumber(statisticsData.usage) }}kWh
        </text>
      </view>
      <view class="divider" />
      <view class="usage-item">
        <text class="usage-label">
          上一次付款时间
        </text>
        <text class="usage-value">
          {{ statisticsData.lastReadDate }}
        </text>
      </view>
    </view>

    <!-- 饼图 -->
    <view class="chart-container">
      <view class="chart-wrapper">
        <l-echart ref="pieChart" />
      </view>
    </view>

    <!-- 用电量分布说明 -->
    <view class="distribution-info">
      <view class="dist-item valley-item">
        <view class="dist-header">
          <view class="dist-icon" style="background-color: #4ECDC4;" />
          <text class="dist-label">
            谷
          </text>
        </view>
        <view class="dist-data">
          <view class="data-row">
            <text class="data-label">
              起始抄表：
            </text>
            <text class="data-value">
              6946kWh
            </text>
          </view>
          <view class="data-row">
            <text class="data-label">
              本次抄表：
            </text>
            <text class="data-value">
              7094kWh
            </text>
          </view>
        </view>
      </view>

      <view class="dist-item flat-item">
        <view class="dist-header">
          <view class="dist-icon" style="background-color: #FFD93D;" />
          <text class="dist-label">
            平
          </text>
        </view>
        <view class="dist-data">
          <view class="data-row">
            <text class="data-label">
              起始抄表：
            </text>
            <text class="data-value">
              12824kWh
            </text>
          </view>
          <view class="data-row">
            <text class="data-label">
              本次抄表：
            </text>
            <text class="data-value">
              12924kWh
            </text>
          </view>
        </view>
      </view>

      <view class="dist-item peak-item">
        <view class="dist-header">
          <view class="dist-icon" style="background-color: #FF6B6B;" />
          <text class="dist-label">
            峰
          </text>
        </view>
        <view class="dist-data">
          <view class="data-row">
            <text class="data-label">
              起始抄表：
            </text>
            <text class="data-value">
              350kWh
            </text>
          </view>
          <view class="data-row">
            <text class="data-label">
              本次抄表：
            </text>
            <text class="data-value">
              410kWh
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 阶梯电量使用情况 -->
    <view class="ladder-section">
      <text class="section-title">
        阶梯电量使用情况
      </text>

      <!-- 阶梯进度条 -->
      <view class="ladder-progress">
        <view class="progress-container">
          <view class="progress-track">
            <!-- 进度条背景 -->
            <view class="progress-bg" />
            <!-- 当前进度 -->
            <view class="progress-fill" :style="{ width: progressWidth }" />
            <!-- 当前位置指示器 -->
            <view class="progress-indicator" :style="{ left: progressWidth }">
              <view class="indicator-dot" />
              <text class="indicator-value">
                {{ currentUsage }}
              </text>
            </view>
          </view>

          <!-- 分界点数值 -->
          <view class="scale-marks">
            <text class="scale-value">
              0
            </text>
            <text class="ladder-label">
              第一阶梯
            </text>
            <text class="scale-value">
              300
            </text>
            <text class="ladder-label">
              第二阶梯
            </text>
            <text class="scale-value">
              700
            </text>
            <text class="ladder-label">
              第三阶梯
            </text>
          </view>
        </view>
      </view>

      <view class="ladder-table">
        <view class="table-header">
          <text class="col-1">
            单价（元/千瓦时）
          </text>
          <text class="col-2">
            用电量（千瓦时）
          </text>
          <text class="col-3">
            金额（元）
          </text>
        </view>
        <view v-for="(item, index) in ladderData" :key="index" class="table-row">
          <view class="row-label">
            {{ item.type }}
          </view>
          <text class="col-1">
            {{ item.price }}
          </text>
          <text class="col-2">
            {{ item.usage }}
          </text>
          <text class="col-3">
            {{ item.amount }}
          </text>
        </view>
      </view>
    </view>

    <!-- 每日用电量统计图表 -->
    <view class="daily-chart">
      <view class="chart-wrapper-bar">
        <l-echart ref="barChart" />
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.electricity-detail {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20rpx;
}

.period-selector {
  background-color: white;
  border-radius: 16rpx;
  padding: 20rpx 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.account-info {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.account-label {
  font-size: 28rpx;
  color: #666;
}

.account-number {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.period-tabs {
  display: flex;
  background-color: #f8f9fa;
  border-radius: 12rpx;
  padding: 6rpx;
  gap: 4rpx;
}

.period-tab {
  padding: 12rpx 24rpx;
  border-radius: 8rpx;
  font-size: 26rpx;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 60rpx;
  text-align: center;

  &.active {
    background-color: white;
    color: #4ecdc4;
    font-weight: 600;
    box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
  }

  &:hover {
    color: #4ecdc4;
  }
}

.top-card {
  background: linear-gradient(135deg, #4ecdc4 0%, #44b3a6 100%);
  border-radius: 20rpx;
  padding: 30rpx 20rpx;
  margin-bottom: 20rpx;
  color: white;
  position: relative;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.date-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: opacity 0.2s ease;

  &:active {
    opacity: 0.7;
  }
}

.report-time {
  font-size: 24rpx;
  opacity: 0.9;
}

.meter-number {
  display: flex;
  align-items: center;
  gap: 10rpx;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
}

.label {
  font-size: 22rpx;
  opacity: 0.8;
}

.number {
  font-size: 22rpx;
}

.amount-section {
  text-align: center;
  margin: 40rpx 0;
}

.total-label {
  display: block;
  font-size: 28rpx;
  opacity: 0.9;
  margin-bottom: 10rpx;
}

.total-amount {
  display: block;
  font-size: 60rpx;
  font-weight: bold;
  color: #ffd93d;
}

.period-info {
  display: flex;
  align-items: center;
  justify-content: center;
}

.period-text {
  font-size: 24rpx;
  opacity: 0.8;
}

.usage-info {
  background-color: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
}

.usage-item {
  flex: 1;
  text-align: center;
}

.usage-label {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.usage-value {
  display: block;
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.divider {
  width: 2rpx;
  height: 80rpx;
  background-color: #e5e7eb;
}

.time-section {
  background-color: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.unit-info {
  font-size: 28rpx;
  color: #666;
}

.chart-container {
  background-color: white;
  border-radius: 16rpx;
  padding: 30rpx 20rpx;
  margin-bottom: 20rpx;
}

.chart-wrapper {
  height: 580rpx;
  width: 100%;
}

.distribution-info {
  background-color: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.dist-item {
  margin-bottom: 30rpx;
  padding: 25rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
  border-left: 4rpx solid #e5e7eb;

  &:last-child {
    margin-bottom: 0;
  }
}

.dist-header {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  gap: 15rpx;
}

.dist-icon {
  width: 24rpx;
  height: 24rpx;
  border-radius: 50%;
}

.dist-label {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.dist-data {
  padding-left: 40rpx;
}

.data-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.data-label {
  font-size: 28rpx;
  color: #666;
}

.data-value {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
}

.valley-item {
  border-left-color: #4ecdc4;
}

.flat-item {
  border-left-color: #ffd93d;
}

.peak-item {
  border-left-color: #ff6b6b;
}

.ladder-section {
  background-color: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.ladder-progress {
  margin: 40rpx 0;
}

.progress-container {
  position: relative;
  height: 80rpx;
}

.progress-track {
  position: relative;
  height: 20rpx;
  background-color: #e5e7eb;
  border-radius: 10rpx;
  margin: 30rpx 0;
}

.progress-bg {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: #e5e7eb;
  border-radius: 10rpx;
}

.progress-fill {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  background: linear-gradient(90deg, #4ecdc4 0%, #ffd93d 70%, #ff6b6b 100%);
  border-radius: 10rpx;
  z-index: 1;
}

.progress-indicator {
  position: absolute;
  transform: translateX(-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 2;
}

.indicator-dot {
  width: 16rpx;
  height: 16rpx;
  background-color: #4ecdc4;
  border-radius: 50%;
  border: 3rpx solid white;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.15);
}

.indicator-value {
  margin-top: -70rpx;
  font-size: 24rpx;
  font-weight: 600;
  color: #333;
  background-color: white;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.scale-marks {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15rpx;
  padding: 0 10rpx;
}

.scale-value {
  font-size: 24rpx;
  font-weight: 600;
  color: #333;
}

.ladder-labels {
  display: flex;
  margin-top: 10rpx;
}

.label-item {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.ladder-label {
  font-size: 20rpx;
  color: #666;
  background-color: #f8f9fa;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  border: 1rpx solid #e5e7eb;
}

.ladder-table {
  margin-top: 20rpx;
}

.table-header {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 2rpx solid #e5e7eb;
  font-weight: 600;
  color: #333;
}

.table-row {
  display: flex;
  align-items: center;
  padding: 25rpx 0;
  border-bottom: 1rpx solid #f3f4f6;

  &:last-child {
    border-bottom: none;
  }
}

.row-label {
  width: 200rpx;
  font-size: 26rpx;
  color: #333;
  font-weight: 500;
}

.col-1,
.col-2,
.col-3 {
  flex: 1;
  text-align: center;
  font-size: 26rpx;
  color: #666;
}

.daily-chart {
  background-color: white;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 40rpx;
}

.chart-wrapper-bar {
  height: 600rpx;
  width: 100%;
}
</style>
